package account.dao.impl;

import account.dao.AccountDao;
import account.entity.AccountVO;
import generic.dao.impl.GenericDaoImpl;
import generic.page.Page;
import generic.page.Pages;

import java.util.List;

public class AccountDaoImpl extends GenericDaoImpl<AccountVO,Integer> implements AccountDao {


    @Override
    public AccountVO findByLoginAccount(String loginAccount) {
        Object[] params={loginAccount};
        List list=this.findObj("from AccountVO a where a.loginAccount=?",params);
        if(list.size() == 0){
            return null;
        }else {
            return (AccountVO) list.get(0);
        }
    }

    @Override
    public AccountVO findAccount(AccountVO accountVO) {
        return findAccountVoById(accountVO.getId());
    }

    @Override
    public void deleteAccountById(Integer id) {
        this.delete(this.findAccountVoById(id));

    }

    @Override
    public AccountVO updateAccount(AccountVO accountVO) {
        this.update(accountVO);
        return accountVO;
    }

    public AccountVO findAccountVoById(Integer id){

        return (AccountVO)this.findById(account.entity.AccountVO.class,id);
    }

    @Override
    public Pages queryForPage(Pages pages) {



        int pageSize=Pages.resetPageSize(pages.getPageSize());
        pages.setPageSize(pageSize);

        String hql1 = "select count(*) from "+AccountVO.class.getName();

        //当前页码
        final   int currentPage = Pages.countCurrentPage(pages.getCurrentPage());
        pages.setCurrentPage(currentPage);

        //总记录数
        Integer rowCount = Integer.parseInt(this.getSession().createQuery(hql1).uniqueResult().toString());
            pages.setRowCount(rowCount);

        //总页数
        final   int totalPage = Pages.countTotalPage(pageSize, rowCount); //总页数
        pages.setTotalPage(totalPage);

        //当前页开始的记录
        final  int offset = Pages.countOffset(pageSize, currentPage); //当前页开始记录

        //判断
        Pages.setPreOrNextBoolean(pages);

        //查询记录
        List list = this.getSession().createQuery("from "+AccountVO.class.getName())
                .setFirstResult(offset)
                .setMaxResults(pageSize).list();
        pages.setList(list);

        return pages;
    }


    public Page queryPage(Integer pageSize, Integer currentPage) {

        StringBuffer hql = new StringBuffer();
        hql.append("select count(*) from AccountVO");
        Integer rowCount = Integer.parseInt(this.getSession().createQuery(hql.toString()).uniqueResult().toString());
        Page page=new Page(pageSize,currentPage,rowCount);

        //查询记录
        List list = this.getSession().createQuery("from AccountVO")
                .setFirstResult(page.getOffset())
                .setMaxResults(page.getPageSize()).list();
        page.setList(list);
        return page;
    }




}
